/*
 * SPDX-License-Identifier: (MIT OR CECILL-C)
 *
 * Copyright (C) 2006-2023 INRIA and contributors
 *
 * Spoon is available either under the terms of the MIT License (see LICENSE-MIT.txt) or the Cecill-C License (see LICENSE-CECILL-C.txt). You as the user are entitled to choose the terms under which to adopt Spoon.
 */
package spoon.template;

import java.lang.reflect.Field;

import spoon.SpoonException;
import spoon.reflect.declaration.CtElement;
import spoon.reflect.factory.Factory;
import spoon.support.template.Parameters;

/**
 * handles the well-formedness and helper methods of templates
 */
public abstract class AbstractTemplate<T extends CtElement> implements Template<T> {

	private boolean addGeneratedBy = false;

	@Override
	public boolean withPartialEvaluation() {
		return false;
	}

	/**
	 * verifies whether there is at least one template parameter.
	 */
	public boolean isWellFormed() {
		return !Parameters.getAllTemplateParameterFields(this.getClass()).isEmpty();
	}

	/**
	 * verifies whether all template parameters are filled.
	 */
	public boolean isValid() {
		try {
			for (Field f : Parameters.getAllTemplateParameterFields(this.getClass())) {
				if (f.get(this) == null) {
					return false;
				}
			}
			return true;
		} catch (Exception e) {
			throw new SpoonException(e);
		}
	}

	/**
	 * returns a Spoon factory object from the first template parameter that contains one
	 */
	public Factory getFactory() {
		return Substitution.getFactory(this);
	}

	/**
	 * @return true if the template engine adds Generated by ... comments into generated code
	 */
	public boolean isAddGeneratedBy() {
		return addGeneratedBy;
	}

	/**
	 * @param addGeneratedBy if true the template engine will add Generated by ... comments into generated code
	 */
	public AbstractTemplate<T> addGeneratedBy(boolean addGeneratedBy) {
		this.addGeneratedBy = addGeneratedBy;
		return this;
	}
}
